package com.xinlong.shop.api.common;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinlong.shop.framework.core.entity.SysFile;
import com.xinlong.shop.framework.service.ISysFileService;
import org.springframework.web.bind.annotation.*;
import com.xinlong.shop.framework.common.R;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Locale;

/**
 * <p>
 * 上传文件
 * </p>
 *
 * @author Sylow
 * @since 2022-11-18
 */
@RestController
@RequestMapping("/uploader")
public class UploaderController {

    private String allowedTypes = "jpg,gif,png,jpeg";

    private final ISysFileService sysFileService;

    public UploaderController(ISysFileService sysFileService) {
        this.sysFileService = sysFileService;
    }

    @PostMapping
    public R upload(MultipartFile file, String scene) {
        try {
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            fileType = fileType.toLowerCase();
            if (allowedTypes.indexOf(fileType) == -1) {
                return R.error("不支持的文件类型");
            }
            SysFile sysFile = sysFileService.upload(file, scene);
            return R.success("操作成功", sysFile);
        }catch (IOException e) {
            return R.error("上传失败", e.getMessage());
        }
    }


}
